/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Row, Col, Card, Button, Tabs, Form, Popconfirm, Modal, Tooltip,Table,Input,InputNumber,message} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps, } from 'utils/view_utils'
import { FloatObj } from "utils/util"
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import cx from 'classnames'
// 当前组件样式
import styles from './biddingStyle.less'
import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import { chunk } from 'lodash'

const FormItem = Form.Item;
const InputGroup = Input.Group;
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 *
 */
console.log('FloatObj',FloatObj)
console.log('FloatObj',FloatObj.add(0.1,0.2))

// 根据字典生成随机序列
let randomCode = function (len,dict) {
  for (var i = 0,rs = ''; i < len; i++)
    rs += dict.charAt(Math.floor(Math.random() * 100000000) % dict.length);
  return rs;
};

// 生成随机手机号码
let  randomPhoneNumber = function(){
  // 第1位是1 第2,3位是3458 第4-7位是* 最后四位随机
  return [1,randomCode(1,'3456789'),randomCode(9,'0123456789')].join('');
};

let productTypeMap={//商品类型
  1:'房源',
  2:'停车位',
  3:'商铺',
  4:'日用快消',
  5:'家电数码',
  6:'首饰箱包',
  7:'其他'
}
const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {loading, btnLoading, modalObj, currentItem, detailInfo, tableData, pageConfig,formData} = modelObj
  // modelObj.xxx获取model中状态机的值
  detailInfo.maxNum = Math.max(detailInfo.initPrice,detailInfo.grads,detailInfo.currentMaxPrice)
  console.log('modelObj', modelObj)
  
  let tableProps = {
    columns: [
      {
        title: '竞拍商品',
        dataIndex: 'goodsName',
        key: 'goodsName',
      },
      {
        title: '商品类型',
        dataIndex: 'productType',
        key: 'productType',
        render:(value,item)=>{
         return  (productTypeMap[value]||'')
        }
      },
      {
        title: '竞拍时间',
        dataIndex: 'startTime',
        key: 'startTime',
      },
      {
        title: '起拍价',
        dataIndex: 'initPrice',
        key: 'initPrice',
      },
      {
        title: '竞拍幅度',
        dataIndex: 'grads',
        key: 'grads',
      },
      {
        title: '当前出价',
        dataIndex: 'currentMaxPrice',
        key: 'currentMaxPrice',
      },
      {
        title: '出价时间',
        dataIndex: 'bidTime',
        key: 'bidTime',
      },
    
    ],
    dataSource: [
      detailInfo
    ],
  }

  // 详情页跳转
  function routerGo ({type, item = {}}) {
    hashHistory.push({
      pathname: '/home/auctions/productEdit',
      query: {pageType: type, id: item.seckillProductId || ''}
    })
  }
  
  
  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  //修改状态
  const inputChange = (value,key) => {
   formData[key]=value
    changeState({formData})
  }
  //查询
  const onSearch = (payload) => {
    dispatch({
      type: `${namespace}/search`,
      payload: payload
    })
  }
  
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'admin/bid/insideBid/queryList',
      // 接口方式
      'method': 'GET',
      'app': '',
      // 接口参数
      'params': `seckillProductId=${modelObj.id || ''}&pageNo=1&pageSize=10`,
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 数据表格
      'table':
        {
          'status_params': 'status=0',
          'status_text': '全部',
          'extProps': {
            title: () => '竞拍者出价记录'
          },
          // 表头字段列表
          'scroll': {x: 1000},
          'fields': [//序号 出价（元） 账号  姓名  类型  出价时间
            {
              'en_name': 'key',
              'zh_name': '序号', width: 60,
              render: (a, item, index, d, e, f) => {
                return (
                  index + 1
                )
              },
            },
            {
              'en_name': 'price',
              'zh_name': ' 出价（元）',
            },
            {
              'en_name': 'mobile',
              'zh_name': '账号',
            },
            {
              'en_name': 'createPerson',
              'zh_name': '姓名',
            },
            {
              'en_name': 'type',
              'zh_name': '类型',
              render: (value, item, index, d, e, f) => {
                return {1: '普通', 2: '内部'}[value]
              },
            },
            {
              'en_name': 'createTime',
              'zh_name': '出价时间',
            }
          ]
        },
      'action_bar': [
        /*        {
                label: '导出',
                type: 'primary',
                onClick: (e, row) => {
                  exportList("add")
                }
              }*/
      ]
    },
  }
  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      console.log(biz)
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }
  // 随机生产手机号
  function randomPhone () {
    let phone=randomPhoneNumber()
    setFieldsValue({'phone':phone})
    formData.phone=phone
    changeState({formData})
  }
  //出价
  function bidding () {
    validateFields((err, values) => {
      if (!err) {
        dispatch({type: `${namespace}/create`})
      }
    })
  }
  
  function validator (rule, value, callback) {
    console.log('validator', rule, value)
    let maxNum = detailInfo.maxNum
    if (isNaN(value)) {
      callback('请输入数字')
    }
    else if (value&&!isNaN(value)) {
      // let mod=FloatObj.subtract(value,detailInfo.initPrice)
      // mod=FloatObj.mod(mod,detailInfo.grads)//取余
      
      // 按加价幅度出价
      let flag=true;
      if(Number(value)>maxNum){
        let num=FloatObj.subtract(value,detailInfo.initPrice)//减
         num=FloatObj.divide(num,detailInfo.grads)//除
        flag=Number.isInteger(num)
      }
      
      if (Number(value)<maxNum||(detailInfo.currentMaxPrice&&(Number(value)<=detailInfo.currentMaxPrice))) {
        callback('出价必须大于起拍价和目前最高价')
      }
      else if (!flag) {
        callback('请按加价幅度出价')
      }
    }
    callback()
  }
  
  return (
    <div className={cx('pageLayout')}>
      <div className="public_listMain">
        <CollapsiblePanels title="商品信息">
          <div >
            <div className='mgb1'>活动名称：{detailInfo.seckillActivityName||''}</div>
            <Table {...tableProps} />
          </div>
        </CollapsiblePanels>
        {/*竞拍者出价记录*/}
        <ListPage pageProps={pageProps} />
        <CollapsiblePanels title="出价">
          <Form>
            <Row>
              <Col className="col" span={8}>
                <FormItem {...formItemLayout} label="虚拟账号" className={cx('flex')}>
                  {getFieldDecorator('phone', {
                    initialValue: formData.phone,
                    rules: [
                      { required: true, whitespace: true, message: '请输入虚拟账号' },
                      {   message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ },
                    ],
                  })(<Input
                        style={{width:'70%'}}
                        // value={formData.phone||''}
                        onChange={(e) => { inputChange(e.target.value, 'phone') }}
                      />)}
                  <Button type="default"  style={{width:'30%'}}  onClick={(e) => {randomPhone()}}>随机生成</Button>
                </FormItem>
              </Col>
              <Col className="col" span={8}>
                <FormItem {...formItemLayout}
                          label="出价" required={true}>
                  {getFieldDecorator('price', {
                    initialValue:formData.price,
/*                    normalize:(value, prevValue, allValues)=>{
                      let min=detailInfo.currentMaxPrice||detailInfo.initPrice||0
                      if(!isNaN(value)&&value>min){
                      
                      }
                      return value;
                    },*/
                    rules: [
                      {required: true, message: '请输入出价', },
                      {
                        validator: validator
                      }
                    ],
                  })(<InputNumber
                    // defaultValue={formData.price}
                    step={detailInfo.grads||0}
                    min={detailInfo.currentMaxPrice||detailInfo.initPrice||0}
                    onChange={(value) => { inputChange(value, 'price') }}
                  />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col className="txtcenter" span={24}>
                <Button type="primary" loading={modelObj.loading}  onClick={(e) => {bidding()}}>确定</Button>
              </Col>
            </Row>
          </Form>
        </CollapsiblePanels>

{/*        <Modal
          title={'详情'}
          width='800px'
          // className="pubBiz_CommonModel"
          visible={modalObj.visible}
          onCancel={() => {updateModal()}}
          footer={null}
        >
        </Modal>*/}
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))

